package com.dns.reset.core;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class ShellUtils {

    private static final Logger logger = LoggerFactory.getLogger(ShellUtils.class);

    public static void main(String[] args) throws Exception {
        //String result = execCmd("java -version", null);
       // System.out.println(result);
    }

    /**
     * 执行系统命令, 返回执行结果
     *
     * @param cmd 需要执行的命令
     * @param dir 执行命令的子进程的工作目录, null 表示和当前主进程工作目录相同
     */
    public static List<String> execCmd(String cmd, File dir){
        StringBuilder result = new StringBuilder();
        List<String> list=new ArrayList<String>();
        Process process = null;
        BufferedReader bufrIn = null;
        BufferedReader bufrError = null;

        try {
            logger.info("准备执行Shell命令 {}",cmd);
            // 执行命令, 返回一个子进程对象（命令在子进程中执行）
            process = Runtime.getRuntime().exec(cmd, null, dir);

            // 方法阻塞, 等待命令执行完成（成功会返回0）
            int status = process.waitFor();
            if(status != 0){
               // logger.error("Failed to call shell's command and the return status's is: " + status);
            }
            // 获取命令执行结果, 有两个结果: 正常的输出 和 错误的输出（PS: 子进程的输出就是主进程的输入）
            bufrIn = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
            bufrError = new BufferedReader(new InputStreamReader(process.getErrorStream(), "UTF-8"));

            // 读取输出
            String line = null;
            while ((line = bufrIn.readLine()) != null) {
                result.append(line).append('\n');
                list.add(line);
            }
            while ((line = bufrError.readLine()) != null) {
                result.append(line).append('\n');
                list.add(line);
            }
            logger.info("Shell命令执行完毕,执行结果为：{}",result.toString());
        }catch (Exception e){
            logger.info("执行Shell命令时发生异常：{} ",e.getMessage());
        } finally {
            closeStream(bufrIn);
            closeStream(bufrError);

            // 销毁子进程
            if (process != null) {
                process.destroy();
            }
        }

        // 返回执行结果
        return list;
    }

    private static void closeStream(Closeable stream) {
        if (stream != null) {
            try {
                stream.close();
            } catch (Exception e) {
                // nothing
            }
        }
    }
}
